import functools
import jwt
from apps.users.models import User
def authenticated_async(method):

    @functools.wraps(method)
    async def wrapper(self, *args, **kwargs):

        tsessionid = self.request.headers.get("tsessionid", None)

        if not tsessionid:
            tsessionid = self.request.headers.get("tesssionid", None)


        if tsessionid:
            try:
                send_data = jwt.decode(tsessionid, self.settings["secret_key"], leeway=self.settings["jwt_expire"], options={"verify_exp": True})
                print(send_data)
                user_id = send_data["id"]

                try:
                    user = await self.application.objects.get(User, id=user_id)
                    self._current_user = user

                    #协程get
                    await method(self, *args, **kwargs)
                except User.DoesNotExist:
                    self.set_status(401)
                    self.finish({})

            except jwt.exceptions.ExpiredSignatureError as e:
                self.set_status(401)
                self.finish({})
            except jwt.exceptions.DecodeError as e:
                self.set_status(401)
                self.finish({})

        else:
            print("登录失败")
            self.set_status(401)
            self.finish({})

    return wrapper